using System;
using System.Collections;

namespace Scenario.WorkflowEngine.DataModel.Common
{
	public class XMLGrants : bOS.XML.Data.XMLObjectSet 
	{
		public const string MAIN_NODE	= "Grants";

		public XMLGrants()
		{
			this.Init();
		}

		public XMLGrants(System.Xml.XmlNode nodeList)
		{
			this.Parse (nodeList);
		}

		override public void Init()
		{
			this.RemoveAll();
		}

		override public void Parse(System.Xml.XmlNode nodeList)
		{
			this.Init();

			System.Xml.XmlNode node;

			for ( int i=0; i<nodeList.ChildNodes.Count;i++)
			{
				node = nodeList.ChildNodes[i];

				switch ( node.Name) 
				{
					case XMLGrant.MAIN_NODE:
						this.Add ( new XMLGrant(node));
						break;
				}
			}
		}

		override public bOS.XML.XMLNode GetXMLNode()
		{
			bOS.XML.XMLNode xmlNode = new bOS.XML.XMLNode(XMLGrants.MAIN_NODE);

			for ( int i=0; i<this.Count;i++)
			{
				xmlNode.AddNode ( this[i].GetXMLNode() );
			}

			return xmlNode;
		}

		public XMLGrant GetGrant(string sType) 
		{
			for ( int i=0; i<this.Count;i++)
			{
				XMLGrant grant = (XMLGrant)this.List[i];

				if ( grant.Type == sType )
					return grant;
			}

			throw new Exception.GrantNotFound("Grant Not Found");
		}

		/** SORTING  FIELDS **/

		public enum SortFields 
		{
			Type,
			Enabled
		}

		/** SORTING METHODS **/


		public void Sort(SortFields sortField, bool isAscending) 
		{
			switch (sortField) 
			{
				case SortFields.Enabled:
					InnerList.Sort(new EnabledComparer());
					break;
				case SortFields.Type:
					InnerList.Sort(new TypeComparer());
					break;
				
			}
			if (!isAscending) InnerList.Reverse();
		}


		private sealed class TypeComparer : IComparer 
		{
			public int Compare(object x, object y) 
			{
				XMLGrant first = (XMLGrant) x;
				XMLGrant second = (XMLGrant) y;
				return first.Type.CompareTo(second.Type);
			}
		}

		private sealed class EnabledComparer : IComparer 
		{
			public int Compare(object x, object y) 
			{
				XMLGrant first = (XMLGrant) x;
				XMLGrant second = (XMLGrant) y;
				return first.Enabled.CompareTo(second.Enabled);
			}
		}

	}
}